package cn.ywyself.extend.directive;

import cn.ywyself.extend.utils.EscapeUtils;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.TemplateException;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;

/**
 * JavaScript字符转义
 *
 * @author : ywyself
 * @created : 2018-10-10 11:29
 */
public class EscapeJavaScriptDirective extends Directive {

    @Override
    public void setExprList(ExprList exprList) {
        if (exprList.length() != 1) {
            throw new ParseException("# directive support one parameter only", location);
        }
        super.setExprList(exprList);
    }

    @Override
    public void exec(Env env, Scope scope, Writer writer) {
        Object value = exprList != null ? exprList.eval(scope) : null;
        if (value == null) {
            value = "";
        } else if (!(value instanceof String)) {
            throw new TemplateException("The parameter pattern of # directive must be String", location);
        }
        write(writer, EscapeUtils.escapeJavaScript((String) value));
    }
}
